﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ComTo8266
{
    public partial class MainDlg : Form
    {
        SynchronizationContext SyncContext = null;

        private Socket clientSocket;
        private Thread receiveThread;
        private bool is_conn;
        public MainDlg()
        {
            InitializeComponent();
            SyncContext = SynchronizationContext.Current;
            is_conn = false;
        }
        ~MainDlg()
        {
            if (clientSocket.Connected)
                clientSocket.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (et_RecvContent.Text.Length == 0 || et_AutoACK.Text.Length == 0)
                return;
            ListViewItem LVI = new ListViewItem(et_RecvContent.Text);
            LVI.Name = et_RecvContent.Text;
            LVI.SubItems.Add(et_AutoACK.Text);
            ls_autoack.Items.Add(LVI);
        }

        public void receiveMsg()
        {
            byte[] result = new byte[1024];
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据  
                    int receiveLength = clientSocket.Receive(result);
                    string resultStr = Encoding.ASCII.GetString(result, 0, receiveLength);

                    //resultStr.Trim();
                    if (resultStr.Length > 0)
                        SyncContext.Post(recvMsg, resultStr);
                }
                catch (Exception)
                {
                    SyncContext.Post(errClose, null);
                    return;
                }
            }
        }

        public void errClose(object nullobj)
        {
            is_conn = false;
            btn_conn.Text = "连接";
        }
        public void connOk(object nullobj)
        {
            receiveThread = new Thread(new ThreadStart(receiveMsg));
            receiveThread.IsBackground = true;
            receiveThread.Start();
            is_conn = true;
            btn_conn.Text = "断开";
        }
        public void sendMsg(object _msg)
        {
            if (clientSocket!=null && clientSocket.Connected)
            {
                string msg = _msg.ToString();
                var buffer = Encoding.ASCII.GetBytes((byte)(0) + "send:" + msg.ToString());
                buffer[0] = (byte)(msg.Length + 5);
                SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
                socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
                clientSocket.SendAsync(socketEventArgs);
            }
        }

        public void setComBaud(int baudRate)
        {
            if (clientSocket != null && clientSocket.Connected)
            {
                string msg = baudRate.ToString();
                var buffer = Encoding.ASCII.GetBytes((byte)(0) + "com:" + baudRate.ToString());
                buffer[0] = (byte)(msg.Length + 4);
                SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
                socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
                clientSocket.SendAsync(socketEventArgs);
            }
        }
        public void recvMsg(object _msg)
        {
            string msg = _msg.ToString();
            ListViewItem LVI = new ListViewItem(msg);
            if (checkBox1.Checked)
            {
                var ite = ls_autoack.Items.IndexOfKey(msg);
                if (ite != -1)
                {
                    sendMsg(ls_autoack.Items[ite].SubItems[1].Text);
                    LVI.SubItems.Add("是");

                }
                else
                {
                    LVI.SubItems.Add("否");
                }
            }
            else
            {
                LVI.SubItems.Add("否");
            }
            listView1.Items.Add(LVI);
        }

        private void CallBackMethod(IAsyncResult asyncresult)
        {
            MainDlg tcpclient = asyncresult.AsyncState as MainDlg;
            try
            {
                if (tcpclient.clientSocket != null)
                {
                    clientSocket.EndConnect(asyncresult);
                    SyncContext.Post(connOk, null);
                }
            }
            catch (Exception)
            {
                SyncContext.Post(errClose, null);
            }
        }

        private void btn_conn_Click(object sender, EventArgs e)
        {
            try
            {
                if (is_conn)
                {
                    btn_conn.Text = "连接";
                    is_conn = false;
                    clientSocket.Close();
                }
                else
                {
                    IPAddress ip = IPAddress.Parse(et_ip.Text);
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    btn_conn.Text = "取消";
                    IAsyncResult res = clientSocket.BeginConnect(new IPEndPoint(ip, 9527), new AsyncCallback(CallBackMethod), this); //配置服务器IP与端口                     
                }
            }
            catch (Exception)
            {
                clientSocket.Close();
                btn_conn.Text = "连接";
                is_conn = false;
                clientSocket.Close();
            }

        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            sendMsg(et_Send.Text);
        }
    }
}
